<template>
  <div class="user-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>用户管理</h2>
        <p>管理系统用户账号和权限</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreateUser">
          <el-icon><Plus /></el-icon>
          新建用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.realName"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            clearable
            style="width: 150px"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="医生" value="doctor" />
            <el-option label="护士" value="nurse" />
            <el-option label="操作员" value="operator" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="userStore.loading"
        :data="userStore.users"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        
        <el-table-column prop="username" label="用户名" min-width="120" sortable="custom">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="realName" label="姓名" min-width="100" sortable="custom" />
        
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        
        <el-table-column prop="phone" label="电话" min-width="120" />
        
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginAt" label="最后登录" width="160" sortable="custom">
          <template #default="{ row }">
            <span v-if="row.lastLoginAt">
              {{ formatDateTime(row.lastLoginAt) }}
            </span>
            <span v-else class="text-muted">从未登录</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="160" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              text
              @click="handleEditUser(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              text
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>
            <el-button
              v-if="row.id !== userStore.userInfo?.id"
              type="danger"
              size="small"
              text
              @click="handleDeleteUser(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <UserForm
      v-model:visible="formVisible"
      :user="currentUser"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user.store'
import UserForm from '@/components/UserForm.vue'

const userStore = useUserStore()

// 响应式数据
const searchForm = reactive({
  username: '',
  realName: '',
  role: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const sortParams = reactive({
  sortBy: 'createdAt',
  sortOrder: 'desc'
})

const formVisible = ref(false)
const currentUser = ref(null)
const isEdit = ref(false)

// 计算属性
const searchParams = computed(() => ({
  ...searchForm,
  page: pagination.page,
  size: pagination.size,
  sortBy: sortParams.sortBy,
  sortOrder: sortParams.sortOrder
}))

// 方法
const loadUsers = async () => {
  try {
    const result = await userStore.getUsers(searchParams.value)
    pagination.total = result.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadUsers()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    role: '',
    status: ''
  })
  pagination.page = 1
  loadUsers()
}

const handleSortChange = ({ prop, order }) => {
  if (order) {
    sortParams.sortBy = prop
    sortParams.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  } else {
    sortParams.sortBy = 'createdAt'
    sortParams.sortOrder = 'desc'
  }
  loadUsers()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadUsers()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadUsers()
}

const handleCreateUser = () => {
  currentUser.value = null
  isEdit.value = false
  formVisible.value = true
}

const handleEditUser = (user) => {
  currentUser.value = { ...user }
  isEdit.value = true
  formVisible.value = true
}

const handleFormSubmit = async (userData) => {
  try {
    if (isEdit.value) {
      await userStore.updateUser(currentUser.value.id, userData)
      ElMessage.success('用户更新成功')
    } else {
      await userStore.createUser(userData)
      ElMessage.success('用户创建成功')
    }
    formVisible.value = false
    loadUsers()
  } catch (error) {
    ElMessage.error(isEdit.value ? '用户更新失败' : '用户创建失败')
  }
}

const handleStatusChange = async (user) => {
  try {
    await userStore.updateUser(user.id, { status: user.status })
    ElMessage.success(`用户已${user.status === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复原状态
    user.status = user.status === 'active' ? 'inactive' : 'active'
    ElMessage.error('状态更新失败')
  }
}

const handleResetPassword = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户 "${user.username}" 的密码吗？重置后的密码为：123456`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用重置密码的API
    // await userStore.resetPassword(user.id)
    ElMessage.success('密码重置成功，新密码为：123456')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '删除用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户删除失败')
    }
  }
}

const getRoleType = (role) => {
  const roleMap = {
    admin: 'danger',
    doctor: 'primary',
    nurse: 'success',
    operator: 'warning'
  }
  return roleMap[role] || 'info'
}

const getRoleText = (role) => {
  const roleMap = {
    admin: '管理员',
    doctor: '医生',
    nurse: '护士',
    operator: '操作员'
  }
  return roleMap[role] || '未知'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-left h2 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
}

.text-muted {
  color: #bdc3c7;
  font-style: italic;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
  }
  
  .filter-card :deep(.el-form) {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-card :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .filter-card :deep(.el-input),
  .filter-card :deep(.el-select) {
    width: 100% !important;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    padding: 16px;
  }
  
  .pagination-wrapper :deep(.el-pagination) {
    justify-content: center;
  }
  
  .pagination-wrapper :deep(.el-pagination .el-pagination__sizes),
  .pagination-wrapper :deep(.el-pagination .el-pagination__jump) {
    display: none;
  }
}
</style>